import React from 'react'
import {
  Form, Button, Table, Empty, Pagination, Spin, Col, Row, Tag,
  DatePicker,
  Popover, Modal, Input, Select, message,
} from 'antd'
import moment from 'moment'

import IconFont from '@/components/IconFont'
import { address } from '@/Utils/apiConfig'
import { cryptoData } from '@/Utils/common'
import request from '@/Utils/fecth'
import regexp from '@/Utils/regexp'
import { checkPermission } from '@/components/AuthComponent/utils'

import './index.less'

const Option = Select.Option
const accountApi = address.account
const roleApi = address.role

export default class User extends React.Component {
  columns = [
    {
      title: '姓名',
      dataIndex: 'identity_name',
      render: (v) => {
        return v || '--'
      },
    },
    {
      title: '用户名',
      dataIndex: 'name',
      render: (v) => {
        return v || '--'
      },
    },
    {
      title: '身份证号码',
      dataIndex: 'id_card',
      render: (v) => {
        return v || '--'
      },
    },
    {
      title: '账户状态',
      dataIndex: 'status',
      render: (v) => {
        return v === 'UNFROZEN' ? <Tag color="success">正常</Tag> : <Tag color="warning">冻结</Tag>
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      render: (v, record) => {
        const roleId = (record.role || {}).id
        const { roleList } = this.state
        const name = (roleList.find(v => v.id === roleId) || {}).name
        return name || '--'
      },
    },
    {
      title: '邮箱',
      dataIndex: 'mail_address',
      render: (v) => {
        return v || '--'
      },
    },
    {
      title: '在线状态',
      dataIndex: 'login_status',
      render: (v) => {
        return v === 'ONLINE' ? <Tag color="success">在线</Tag> : <Tag color="error">离线</Tag>
      },
    },
    {
      title: '账户有效期至',
      dataIndex: 'expireTime',
      render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '长期有效',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      render: (text, record, index) => {
        const type = (record.role || {}).type
        if (type === 'DEFAULT') {
          return false
        }
        return <div className="action" id={`popver${index}`} style={{ position: 'relative' }}>
          {
            checkPermission('user-account-update') &&
        <span className={`common-operation`} onClick={() => this.modify(record)}>修改</span>
          }
          {
            checkPermission('user-account-frozen') &&
          <span className={`common-operation`} onClick={() => this.handleFrozen(record)}>
            {record.status === 'FROZEN' ? '解冻' : '冻结'}
          </span>
          }
          {
            checkPermission('user-account-resetPWd') &&
        <span className={`common-operation`} onClick={() => this.resetPasswd(record)}>重置密码</span>
          }
          {
            checkPermission('user-account-delete') &&
        <span className={`common-operation`} onClick={() => this.delete(record)}>删除</span>
          }
        </div>
      },
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      list: [],
      total: 0,
      visible: false,
      modalLoading: false,
      roleList: [],
    }
    this.handleRecord = {}
    this.searchOption = {
      pageNum: 1,
      pageSize: 10,
    }
    this.flag = 'create'
  }

  componentDidMount() {
    this.getList()
    this.getRoleList()
  }

  getList = async(values = {}) => {
    this.setState({
      loading: true,
    })
    this.searchOption = {
      ...this.searchOption,
      ...values,
    }
    const { code, data = {}} = await request().get(accountApi.accountList, {
      params: {
        ...this.searchOption,
      },
    })
    this.setState({
      loading: false,
    })
    if (code === 200) {
      this.setState({
        list: data.result || [],
        total: data.total || 0,
      })
    }
  }

  search = (values) => {
    const { role = '', fuzzy = '', temporary = '', status = '' } = values || {}
    this.searchOption.pageNum = 1
    this.searchOption.role = role
    this.searchOption.fuzzy = fuzzy
    this.searchOption.temporary = temporary
    this.searchOption.status = status
    this.getList()
  }

  /**
   * 重置
   */
  cancelSearch = () => {
    this.searchForm.resetFields()
    this.searchForm.submit()
  }

  onPageChange = (current, pageSize) => {
    const { searchOption } = this
    searchOption.pageNum = current
    searchOption.pageSize = pageSize
    this.getList()
  };

  /**
   * 获取所有角色
   */
  getRoleList = async() => {
    const { status, data = {}} = await request().get(roleApi.getList, {
      params: {
        pageNum: 1,
        pageSize: 100,
      },
    })
    if (status === 200) {
      this.setState({
        roleList: (data.data || []).map(v => {
          return {
            ...v,
            id: v.id,
            name: v.name,
            desc: v.desc,
            type: v.type,
          }
        }),
      })
    }
  }

  /**
   *
   * @param {冻结/解冻} record
   */
  handleFrozen = (record) => {
    this.handleRecord = record
    Modal.confirm({
      title: `是否${record.status === 'FROZEN' ? '解冻' : '冻结'}账户${record.name}？`,
      onOk: async() => {
        const { code } = await request().post(accountApi.updateStatus, {
          userId: record.id,
          status: record.status === 'FROZEN' ? 'UNFROZEN' : 'FROZEN',
        })
        if (code === 200) {
          message.success(`${record.status === 'FROZEN' ? '解冻' : '冻结'}成功`)
          this.getList()
        }
      },
    })
  }

  /**
   *
   * @param {重置密码} record
   */
  resetPasswd = (record) => {
    Modal.confirm({
      title: `确定要重置用户名为${record.name}的密码吗？`,
      content: `重置后，该账户密码为“!qwer1234”`,
      onOk: async() => {
        const { code } = await request().post(accountApi.resetPwd, {
          userId: record.id,
        })
        if (code === 200) {
          message.success('操作成功')
          this.getList()
        }
      },
    })
  }

  delete = (record) => {
    Modal.confirm({
      title: `确定删除${record.name}吗？`,
      content: '操作记录等账户数据都会保留，可再次创建同用户名的账户继承这些数据',
      onOk: async() => {
        const { code } = await request().post(accountApi.delete, {
          userId: record.id,
        })
        if (code === 200) {
          Modal.info({
            title: '已提交申请，请等待管理员审核',
            okText: '我知道了',
            cancelText: '',
            onOk: () => {
            },
          })
          this.getList()
        }
      },
    })
  }

  /**
   * 确定添加/修改账户
   */
  onOk = () => {
    this.addForm && this.addForm.validateFields().then(async(values) => {
      this.flag === 'update' ? this.onUpdate(values) : this.onCreate(values)
    })
  }

  onCreate = async(values = {}) => {
    const { expireTime } = values
    const params = {
      ...values,
      expireTime: expireTime ? moment(expireTime).format('YYYY-MM-DD HH:mm:ss') : '',
    }
    const { publicKey } = this.props
    const { code } = await request().post(accountApi.addAccount, cryptoData(JSON.stringify(params), publicKey)
    )
    if (code === 200) {
      Modal.info({
        title: '已提交申请，请等待管理员审核',
        okText: '我知道了',
        onOk: () => {
        },
      })
      this.setState({
        visible: false,
      })
      this.getList()
    }
  }

  onUpdate = async(values) => {
    const { expireTime } = values || {}
    const params = {
      ...values,
      userId: this.handleRecord.id,
      expireTime: expireTime ? moment(expireTime).format('YYYY-MM-DD HH:mm:ss') : '',
    }
    const { code } = await request().post(accountApi.updateAccount, params)
    if (code === 200) {
      Modal.info({
        title: '已提交申请，请等待管理员审核',
        okText: '我知道了',
        onOk: () => {},
      })
      this.setState({
        visible: false,
      })
      this.getList()
    }
  }

  /**
   * 添加账户
   */
  addAccount = () => {
    this.handleRecord = {}
    this.flag = 'create'
    this.setState({
      visible: true,
    })
  }

  /**
   *
   * @param {修改账户} record
   */
  modify = async(record) => {
    this.flag = 'update'
    const { code, data = {}} = await request().get(accountApi.detail.format({ id: record.id }))
    if (code === 200) {
      this.handleRecord = {
        ...data,
        expireTime: record.expireTime ? moment(record.expireTime) : null,
      }
      this.setState({
        visible: true,
      })
    }
  }

  render() {
    const { list, loading, total, visible, modalLoading, roleList } = this.state
    return <div className="User">
      <Form ref={c => this.searchForm = c} className="searchForm" layout="inline" onFinish={this.search}>
        <Form.Item label="搜索" name="fuzzy">
          <Input style={{ width: '250px' }} placeholder="请输入用户名、姓名或者邮箱"/>
        </Form.Item>
        <Form.Item label="角色" name="role">
          <Select style={{ width: '125px' }} placeholder="请选择">
            {
              roleList.map(v => {
                return <Option value={v.id} key={v.id}>{v.name}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="账户类型" name="temporary">
          <Select style={{ width: '125px' }} placeholder="请选择">
            <Option value={0}>长期有效账户</Option>
            <Option value={1}>临时账户</Option>
          </Select>
        </Form.Item>
        <Form.Item label="账户状态" name="status">
          <Select style={{ width: '125px' }} placeholder="请选择">
            {
              AccountStatus.map(v => {
                return <Option key={v.value} value={v.value}>{v.label}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item className="mb24">
          <Button type="primary" htmlType="submit">
          查询
          </Button>
        </Form.Item>
        <Form.Item className="mb24">
          <Button onClick={this.cancelSearch}>
          重置
          </Button>
        </Form.Item>
        {
          checkPermission('user-account-add') &&
          <Form.Item style={{ marginLeft: 'auto' }}>
            <Button type="primary" onClick={() => this.addAccount()}>
          新建账户
            </Button>
          </Form.Item>
        }

      </Form>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <Table
          columns={this.columns}
          className={list.length ? '' : 'empty-list'}
          dataSource={list}
          rowKey="id"
          pagination={false}
          loading={loading}
        />
        {
          !list.length &&
            <Empty className="mt24" />
        }
      </div>

      <div className="pagination-box mt24">

        {
          list.length > 0 &&
            <Pagination
              current={this.searchOption.pageNum}
              pageSize={this.searchOption.pageSize}
              total={total}
              showSizeChanger
              onChange={this.onPageChange} />
        }
      </div>
      <Modal
        centered
        destroyOnClose
        className={'fileEdit parentClass'}
        wrapClassName={`fileEdit`}
        title={`${this.flag === 'update' ? '修改' : '新增'}账户`}
        onCancel={() => this.setState({ visible: false })}
        visible={visible}
        onOk={this.onOk}
        width={800}
        maskClosable={false}
      >
        <Spin spinning={modalLoading}>
          <Form
            ref={c => { this.addForm = c }}
            {...{
              labelCol: { span: 8 },
              wrapperCol: { span: 16 },
            }}
            colon={false}
            autoComplete="false"
            initialValues={this.handleRecord}
          >
            <Row>
              <Col span={12}>
                <Form.Item
                  label="姓名："
                  name="identity_name"
                  rules={[
                    { required: true, message: '请输入用户名' },
                  ]}>
                  <Input maxLength={30} placeholder="请输入用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="角色："
                  name="role"
                  rules={[
                    { required: true, message: '请选择角色' },
                  ]}>
                  <Select style={{ width: '250px' }} placeholder="请选择">
                    {
                      roleList.filter(v => v.type !== 'DEFAULT').map(v => {
                        return <Option value={v.id} key={v.id}>{v.name}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  label="登录用户名："
                  name="name"
                  rules={[
                    { required: true, message: '请输入登录用户名' },
                    {
                      type: 'string',
                      pattern: /^[a-zA-Z]{6,20}$/,
                      max: 20,
                      min: 6,
                      message: '请输入6-20位的英文用户名',
                    },
                  ]}>
                  <Input
                    // disabled={this.flag === 'update'}
                    maxLength={30}
                    placeholder="请输入登录用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="邮箱："
                  name="mail_address"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    {
                      pattern: regexp.email,
                      message: '请输入正确的邮箱地址',
                    },
                  ]}>
                  <Input maxLength={30} placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
            </Row>
            {
              this.flag !== 'update' &&
              <Row>
                <Col span={12}>
                  <Form.Item
                    label="密码："
                    name="_pwd"
                    validateFirst
                    rules={[
                      { required: true, message: '请输入密码' },
                      {
                        type: 'string',
                        min: 8,
                        pattern: regexp._pwd,
                        message: '密码须为8位以上字母数字与特殊字符的组合',
                      },
                    ]}>
                    <Input.Password disabled={this.flag === 'update'} maxLength={30} placeholder="请输入密码" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    dependencies={['_pwd']}
                    label="确认密码："
                    name="confirm__pwd"
                    validateFirst
                    rules={[
                      { required: true, message: '请输入密码' },
                      {
                        type: 'string',
                        min: 8,
                        pattern: regexp._pwd,
                        message: '密码须为8位以上字母数字与特殊字符的组合',
                      },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('_pwd') === value) {
                            return Promise.resolve()
                          }
                          return Promise.reject(new Error('密码两次输入不一致'))
                        },
                      }),
                    ]}>
                    <Input.Password disabled={this.flag === 'update'} maxLength={30} placeholder="请输入密码" />
                  </Form.Item>
                </Col>
              </Row>
            }
            {
              // this.flag !== 'update' &&
              <Form.Item
                name="id_card"
                label="身份证号码："
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                rules={[
                  {
                    required: true,
                    message: '请输入身份证号码',
                  },
                  {
                    pattern: regexp.idCard,
                    message: '请输入正确的身份证号码',
                  },
                ]}
              >
                <Input maxLength={30} className="input" placeholder="请输入身份证号码" />
              </Form.Item>
            }
            <Row>
              <Col span={12}>
                <Form.Item
                  name="temporary"
                  label={<span>
                    账户类型
                    <Popover arrowPointAtCenter content={'临时账户超过有效期后将不允许登录系统'}>
                      <IconFont className="cursor warn" type="ic-tishi1" style={{ margin: '0 2px', fontSize: '14px' }} />
                    </Popover>
                    ：
                  </span>}
                  rules={[{
                    required: true,
                    message: '请选择账户类型',
                  }]}
                >
                  <Select placeholder="请选择">
                    <Option value={0}>长期有效账户</Option>
                    <Option value={1}>临时账户</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={10} style={{ marginLeft: '8px' }}>
                <Form.Item
                  noStyle
                  dependencies={['temporary']}
                >
                  {
                    ({ getFieldValue }) => {
                      return getFieldValue('temporary') === 1 && <Form.Item
                        name="expireTime"
                        rules={[{
                          required: true,
                          message: '请选择失效日期',
                        }]}
                        extra={'账户的失效日期'}
                        wrapperCol={{
                          span: 20,
                        }}
                      >
                        <DatePicker
                          style={{ width: '200px' }}
                          showTime
                          format="YYYY-MM-DD HH:mm:ss"
                          disabledDate={current => {
                            return current && (current > moment().add(90, 'days').endOf('day') || current < moment().endOf('day'))
                          }}
                        />
                      </Form.Item>
                    }
                  }
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="description"
              label="备注："
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
            >
              <Input.TextArea maxLength={150} rows={5} className="input" placeholder="请输入备注" />
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </div>
  }
}

const AccountStatus = [
  {
    label: '正常',
    value: 'UNFROZEN',
  },
  {
    label: '冻结',
    value: 'FROZEN',
  },
]
